<template>
  <div :class="state.type === 'see' ? 'room-add-form see-form' : 'room-add-form'">
    <DynamicForm ref="dynamicFormRef" @click="callBack" :refresh="state.refresh" :rulesForm="state.rulesForm"
                 :rules="state.rules" :type="state.type"/>
  </div>
</template>

<script lang="ts" setup>
import {ref, onMounted, reactive, defineEmits} from 'vue';
import {useRoute} from 'vue-router'

import DynamicForm from '@/components/layout/form/dynamic-form.vue';
import {
  defaultForms,
  defaultRules,
  floorForms,
  floorRules,
  roomForms,
  roomRules
} from '@/assets/script/monitor/forms/room/add-form';
import {insertBmsConstApi, listFindByBmsConstVoApi, modifyBmsConstApi} from "@/api/room";
import {ElMessage} from 'element-plus';
import {bedAddForms} from "@/assets/script/monitor/forms/bed/add-form";

const dynamicFormRef = ref(DynamicForm)

const emits = defineEmits<{ (e: 'appClick', data: object): void }>();

const router = useRoute()

const state = reactive({
  rulesForm: [],
  rules: {},
  refresh: null as any,
  id: null as any,
  type: 'form'
})

onMounted(() => {
  console.log('router.query', router.query)
  if (router.query) {
    state.id = router.query.id
    findConst()
  }
  if (router.path?.indexOf('see-') > -1) {
    state.type = 'see'
  }

  state.rulesForm = JSON.parse(JSON.stringify(defaultForms))
  state.rulesForm = defaultForms;
  state.rules = defaultRules;
  state.refresh = Math.random()
})

const callBack = (data: any) => {
  switch (data.type || '') {
    case 'dictionaryCode':
      switch (data.data || '') {
        case 'floor':
          listFindByBmsConstVo(['storey'])
          break
        case 'room':
          listFindByBmsConstVo(['storey', 'floor'])
          break
        default:
          state.rulesForm = defaultForms;
          state.rules = defaultRules;
          state.refresh = Math.random()
          break
      }
      break
    case 'submit':
      // eslint-disable-next-line no-case-declarations
      let params = data.data
      if (params.parentCodes && params.parentCodes.length > 0) {
        params['parentCode'] = params.parentCodes[params.parentCodes.length - 1]
      }
      if (params.dictionaryCodeName) {
        params['dictionaryName'] = params.dictionaryCodeName
      }
      modifyBmsConst(params)
      break
    default:
      console.log('callBack', data)
      break
  }
}

const modifyBmsConst = (params: any) => {
  if (state.id) {
    modifyBmsConstApi(params).then((data: any) => {
      if (data.code === 0) {
        ElMessage.success('修改成功！')
        emits('appClick', {type: 'closeTab', data: router.path})
        state.refresh = Math.random()
      } else {
        ElMessage.warning('修改失败！')
      }
    })
  } else {
    insertBmsConstApi(params).then((data: any) => {
      if (data.code === 0) {
        ElMessage.success('添加成功！')
        emits('appClick', {type: 'closeTab', data: router.path})
        state.refresh = Math.random()
      } else {
        ElMessage.warning('添加失败！')
      }
    })
  }
}

const findConst = () => {
  const dictionary = router.query.dictionary
  // 先查询信息
  if (dictionary && dictionary !== 'storey') {
    debugger
    listFindByBmsConstVo(dictionary === 'floor' ? ['storey'] : ['floor', 'storey'])
  } else {
    listFindByBmsConstVoById();
  }
}

const listFindByBmsConstVoById = async () => {
  if (!router.query || !router.query.id || !router.query.code) {
    state.refresh = Math.random()
    return false
  }
  const id = router.query.id
  const constCode = router.query.code
  await listFindByBmsConstVoApi({id, constCode}).then((data: any) => {
    const card = state.rulesForm[0]?.card || []
    for (let i in card) {
      let e = card[i]
      if (e.line) {
        continue
      }
      const name = e.name === 'parentCodes' ? 'parentCode' : e.name
      const value = data[0][name]
      if (value && e.name !== 'parentCodes') {
        e[name] = value
      } else if (e.name === 'parentCodes') {
        for (let k in e.options) {
          let opt = e.options[k]
          const item = opt.children.find((o: any) => o.value === value)
          if (!item)
            continue
          e['parentCodes'] = [opt.value, value]
          break
        }
      }
    }
  })
  state.refresh = Math.random()
  console.log('state.rulesForm', state.rulesForm)
}

const listFindByBmsConstVo = (params = [] as any) => {
  listFindByBmsConstVoApi({dictionaryCodeList: params}).then((data: any) => {
    if (params.includes('floor')) {
      const names = ['parentCodes', 'parentCode']
      let item = roomForms[0].card.find(({name = ''}) => names.includes(name))
      const storeyList = data.filter((f: any) => f.dictionaryCode === 'storey')
      storeyList?.forEach((e: any) => {
        const room = data.filter((f: any) => f.parentCode === e.constCode)
        let storey = {label: e.constName, value: e.constCode, children: []}
        room.forEach((r: any) => {
          storey.children.push({label: r.constName, value: r.constCode})
        })
        item.options.push(storey)
      })
      state.rulesForm = JSON.parse(JSON.stringify(roomForms));
      state.rules = roomRules;
      listFindByBmsConstVoById();
    } else {
      let item = floorForms[0].card.find(({name = ''}) => name === 'parentCode')
      data.forEach((e: any) => {
        item.options.push({label: e.constName, value: e.constCode})
      })
      state.rulesForm = JSON.parse(JSON.stringify(floorForms));
      state.rules = floorRules;
      state.refresh = Math.random()
    }
  })
}

</script>